package com.lenl.arithmetic.tenusablealgorithm.binarysearchnocursion;

/**
 * @author Lenl
 * @version v1.0
 * @create 2022-05-14 11:03
 * @description 非递归二分查找
 */
public class BinarySearchNoRecur {
    public static void main(String[] args) {
        //测试
        int[] arr={1,3,4,5,7,9,56};
        int index=binarySearch(arr,3);
        System.out.println(index);

    }

    //二分查找的非递归实现
    public static  int binarySearch(int[] arr ,int target){
        int left=0;
        int right=arr.length-1;
        while(left<=right){
            //说明继续查找
            int mid=(left+right)/2;
            if(arr[mid]==target){
                return mid;
            }else if(arr[mid]>target){
                right=mid-1;//向左边查找
            }else{
                left=mid+1;
            }
        }
        //未找到
        return -1;
    }

}
